﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EvidenceLib.Core;
using NHibernate;

namespace EvidenceService.Core
{
    public class BasicService<T> where T : class,IKey
    {
        protected ISession mSession;

        public BasicService(ISession session)
        {
            mSession = session;
        }

        public virtual T LoadById(int id)
        {
            return this.mSession.Load<T>(id);
        }

        public virtual IList<T> LoadByHQL(string hql)
        {
            return this.mSession.CreateQuery(hql).List<T>();
        }

        public virtual Tuple<IList<object[]>, int> LoadObjsBySQLWithPaging(string sql, string totalSql, int pageSize, int pageIndex)
        {
            IList<object[]> ls = new List<object[]>();
            try
            {
                //查询行记录数综合
                int total = (int)mSession.CreateSQLQuery(totalSql).UniqueResult<long>();
                IQuery q = mSession.CreateSQLQuery(sql);
                ls = q.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).List<object[]>();

                return new Tuple<IList<object[]>, int>(ls, total);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public virtual Tuple<IList<T>, int> LoadListByHQLWithPaging(string hql, string totalHql, int pageSize, int pageIndex)
        {
            IList<T> ls = new List<T>();
            try
            {
                //查询行记录数综合
                int total = (int)mSession.CreateQuery(totalHql).UniqueResult<long>();
                IQuery q = mSession.CreateQuery(hql);
                ls = q.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).List<T>();

                return new Tuple<IList<T>, int>(ls, total);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public virtual void SaveOrUpdate(T entity)
        {
            //this.mSession.Merge<T>(entity);
            //this.mSession.Clear();

            this.mSession.SaveOrUpdate(entity);
        }

        public virtual void DeletebyHQL(string hql)
        {
            this.mSession.CreateQuery(hql).ExecuteUpdate();
            this.mSession.Flush();
        }


        public virtual void Flush()
        {
            this.mSession.Flush();
        }
    }
}
